<template>
  <div class="p-2" style="border-top: 1px solid var(--border)">
    <!-- 输入框工具 -->
    <div class="flex flex-row items-center gap-5 cursor-pointer">
      <!-- 表情选择 -->
      <n-popover style="padding: 0" trigger="click">
        <template #trigger>
          <component :is="RenderIcon(HappyOutline, 'text-xl')"></component>
        </template>
        <EmojiPicker :native="true" @select="SelectEmojiPicker" />
      </n-popover>

      <!-- 文件上传 -->
      <el-upload :auto-upload="false" :multiple="true" :show-file-list="false" action="" @change="HandleFileSelect">
        <template #trigger>
          <component :is="RenderIcon(FolderOutline, 'text-xl')"></component>
        </template>
      </el-upload>

      <!-- 图片上传 -->
      <el-upload
        :accept="'image/*'"
        :auto-upload="false"
        :multiple="true"
        :show-file-list="false"
        action=""
        @change="HandelPaste"
      >
        <template #trigger>
          <component :is="RenderIcon(ImageOutline, 'text-xl')"></component>
        </template>
      </el-upload>

      <!-- 截图 -->
      <n-popover style="background-color: var(--bg-center); padding: 5px" trigger="click">
        <template #trigger>
          <component :is="RenderIcon(CropOutline, 'text-xl')"></component>
        </template>
        <div class="text-base text-fontPrimary flex flex-col item-center cursor-pointer">
          <p class="p-2 hover:bg-CenterHover rounded" @click="TriggerScreenshot('window')">截取窗口</p>
          <p class="p-2 hover:bg-CenterHover rounded" @click="TriggerScreenshot('screen')">截图全屏</p>
        </div>
      </n-popover>
    </div>

    <!-- 输入框 -->
    <div
      id="message-input"
      ref="messageInput"
      contenteditable="true"
      @click="updateSelectionRange"
      @compositionend="updateSelectionRange"
      @input="HandelInput"
      @keydown="updateSelectionRange"
      @keyup="updateSelectionRange"
      @keydown.exact.enter.prevent="Send"
      @keydown.exact.meta.enter.prevent="Send"
    ></div>

    <!-- 发送按钮 -->
    <div class="text-right pr-4">
      <el-button :disabled="DisabledSend" size="small" type="primary" @click="Send">发送 </el-button>
    </div>
  </div>

  <!-- @框 用户输入@触发-->
  <div v-if="Ait" id="AitMention" class="w-[140px] overflow-y-scroll rounded bg-Center p-1">
    <div>
      <div
        v-for="item in FilterMemberList"
        class="flex flex-row items-center gap-2 hover:bg-CenterHover cursor-pointer p-2"
        @click="HandelAit(item)"
      >
        <n-avatar round :src="item.avatar" size="medium"></n-avatar>
        <p>{{ item.name }}</p>
      </div>
    </div>
  </div>
  <!-- 上传弹窗 -->
  <n-modal
    v-model:show="showDialog"
    aria-modal="true"
    role="dialog"
    size="huge"
    style="width: 300px; background-color: var(--bg-center); padding: 5px"
  >
    <div class="flex flex-col gap-2 rounded text-fontPrimary">
      <!-- 头部 -->
      <div style="border-bottom: 1px solid var(--border)">
        <p class="text-xs text-fontPlaceholde">发送给：</p>
        <div class="flex flex-row items-center gap-1 p-2">
          <n-avatar :src="ChatObject!.avatar" size="medium" />
          {{ ChatObject!.name }}
        </div>
      </div>
      <!-- 文件列表 -->
      <div class="w-full h-[200px] overflow-scroll">
        <div
          v-for="(item, index) in selectFile"
          :key="index"
          class="flex flex-row justify-between items-center gap-2 cursor-pointer p-2 rounded-sm hover:bg-CenterHover"
        >
          <!-- 文件图片 -->
          <n-avatar :size="50" :src="item?.viewUrl ?? ''" />
          <!-- 文件信息 -->
          <div class="flex-1 flex flex-col justify-between gap-2">
            <p class="text-sm text-ellipsis font-semibold">
              {{ item?.file.name }}
            </p>
            <p class="text-xs">{{ FormatFileSize(item?.file.size) }}</p>
          </div>
          <!-- 删除 -->
          <Trash class="w-[16px] h-[16px] hover:text-red-600" @click="RemoveSelectFile(item)"></Trash>
        </div>
      </div>
      <!-- 按钮 -->
      <div class="text-right p-2">
        <el-button size="small" @click="showDialog = false">取消</el-button>
        <el-button size="small" type="primary" @click="SendUpload"> 发送 </el-button>
      </div>
    </div>
  </n-modal>
</template>

<script lang="ts" setup>
import { nextTick, ref } from "vue";
import { storeToRefs } from "pinia";
import { IGroupMemberInfo } from "@/types/group.ts";
import { IFile, IMessage, MessageType } from "@/types/chat.ts";
import { useChat } from "@/store/modules/chat.ts";
import { useCommon } from "@/hooks/useCommon.ts";
import { useInput } from "@/hooks/useInput.ts";
import { useMitt } from "@/hooks/useMitt.ts";
import { RenderIcon } from "@/utils/common.ts";
import { MessageStrategyMap } from "@/tactics/message.ts";
import { FormatFileSize, HandelFileUploadProgress, ViewImageFile } from "@/utils/file.ts";
import { NAvatar, NModal, NPopover } from "naive-ui";
import { CropOutline, FolderOutline, HappyOutline, ImageOutline, Trash } from "@vicons/ionicons5";
import EmojiPicker from "vue3-emoji-picker";
import ReferMention from "@/components/Message/components/ReferMention.vue";
import "vue3-emoji-picker/css";

const messageInput = ref<HTMLDivElement | null>(null);
const { HandelInput, Focus, updateSelectionRange, Ait, ActiveQuotationId, FilterMemberList, Send, DisabledSend } =
  useInput(messageInput);
const { TriggerInputEvent, InsertImgNode, InsertTextNode, InsertAitNode, GetEditor, InsertReferMenNode } = useCommon();
const chat = useChat();
const { ChatObject } = storeToRefs(chat);
let selectFile = ref<IFile[]>([]);
let showDialog = ref<boolean>(false);

//打开截图
async function TriggerScreenshot(type: "window" | "screen") {
  window.electronApi.openScreenShot(type);
}

// 添加文件
async function HandleFileSelect(file: any) {
  showDialog.value = true;
  selectFile.value = [];
  selectFile.value.push(await ViewImageFile(file.raw));
}

// 移除选择的文件
function RemoveSelectFile(item: IFile) {
  selectFile.value = selectFile.value.filter((v) => v !== item);
  if (selectFile.value.length === 0) showDialog.value = false;
}

// 点击发送消息并且上传文件
async function SendUpload() {
  const strategy = MessageStrategyMap[MessageType.file];
  const result = strategy.getMsg({
    files: selectFile.value,
  });
  if (!result) return;
  const { message, file } = result;
  showDialog.value = false;
  await HandelFileUploadProgress(message, file!);
}

// 插入表情
function SelectEmojiPicker(emoji: any) {
  if (!messageInput.value) return;
  Focus(messageInput.value);
  InsertTextNode(messageInput.value, emoji.i);
  TriggerInputEvent(messageInput.value);
}

// 插入图片
function HandelPaste(file: any) {
  if (!messageInput.value) return;
  Focus(messageInput.value);
  InsertImgNode(file.raw, messageInput.value!);
}

// 插入ait
function HandelAit(item: IGroupMemberInfo) {
  if (!messageInput.value) return;
  Focus(messageInput.value);
  const { range } = GetEditor()!;
  const textNode = range?.endContainer;
  // 把选区移动到@ 目的是为了删除 @ 然后再添加 @xxx
  if (textNode) {
    const endOffset = range.endOffset;
    const textNodeValue = textNode?.nodeValue as string;
    const expRes = /@([^@]*)$/.exec(textNodeValue);
    if (expRes) {
      range.setStart(textNode, expRes.index);
      range.setEnd(textNode, endOffset!);
    }
  }
  InsertAitNode("@", item.name, {} as HTMLElement);
  TriggerInputEvent(messageInput.value);
  Ait.value = false;
}

// 插入引用
function MountQuotation(item: IMessage) {
  if (!messageInput.value) return;
  ActiveQuotationId.value = item.uuid;
  InsertReferMenNode(messageInput.value, ReferMention, { quotationId: item.uuid });
  updateSelectionRange();
}

// 获取截图的数据
window.electronApi.getCutScreenResult((data: any) => {
  nextTick(() => {
    InsertImgNode(data, messageInput.value!);
  });
});

useMitt.on("aitMention", HandelAit);
useMitt.on("quotation", MountQuotation);
</script>

<style lang="scss" scoped>
#message-input {
  width: 100%;
  height: 80px;
  overflow-x: hidden;
  border: none;

  &:focus {
    border-color: transparent;
    outline: none;
  }

  padding: 5px;
}
</style>
